<!--
 * @Description: 告警类别管理
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="22"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-save="false"
        :has-cancel="false"
        :has-edit="false"
        :has-edit-column="true"
        @showColumn="showColumn"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm
        :form-config="formConfig"
        :form-data="searchlist"
        @search="search"
      />
    </template>
    <template v-slot:table-box>
      <Table
        v-loading="loading"
        :prop-list="tableColumn"
        :list-data="tableData"
        @sortChange="changeTableSort"
        @handleSelectionChange="handleSelectionChange"
      >
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="judgePermission(22, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(row)"
            ><i class="el-icon-edit-outline"></i> 修改</el-button>
            <el-button
              v-if="judgePermission(22, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row.alarmTypeId)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '告警类别信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <!-- :show-message="canInput" -->
        <el-form
          ref="formData"
          label-position="left"
          :rules="rules"
          :model="formData"
          class="el-form"
        >
          <el-form-item label="告警类别名称:" class="w50p" prop="alarmTypeName">
            <el-input v-model="formData.alarmTypeName" clearable />
          </el-form-item>
          <el-form-item label="告警类别描述:" class="w50p" prop="describe">
            <el-input v-model="formData.describe" clearable />
          </el-form-item>
          <el-form-item
            v-if="nowChanceStau === 'add' || nowChanceStau === 'edit'"
            label="数据类型选择"
            class="w50p"
            prop="nowdataType"
          >
            <el-select
              v-model="nowdataType"
              clearable
              multiple
              @change="addDataType"
            >
              <el-option
                v-for="(item, index) in dataTypeList"
                :key="item.dataTypeId"
                :value="item.dataTypeId"
                :label="item.dataTypeName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="所关联数据类型:" class="w100p">
            <div class="contact-view">
              <div
                v-for="(item, index) in showdatatypeList"
                :key="index"
                class="contact-view-but"
                @click="delDataType(index)"
              >
                {{ item.dataTypeName }}
                <i
                  v-if="nowChanceStau === 'add' || nowChanceStau === 'edit'"
                  class="el-icon-close"
                ></i>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :table-column="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button
            class="zh-button-one"
            @click="dialogTableColumnVisible = false"
          >
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="saveColumn">
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from "@/components/searchForm";
import Table from "@/components/table/table.vue";
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/monitoring-alarm/alarm-category-management";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";
export default {
  name: "AlarmCategoryManagement",
  components: { Table, ActionBar, Pagination, BaseMainSlot, SearchForm },
  mixins: [mymixin],
  data() {
    var validatePass = (rule, value, callback) => {
      if (this.nowdataType === null || this.nowdataType.length === 0) {
        callback(new Error("请输入选择数据类型"));
      } else {
        callback();
      }
    };
    return {
      tableColumn: [
        { prop: "alarmTypeName", label: "告警类别名称" },
        { prop: "describe", label: "告警类别描述" },
        {
          prop: "operation",
          label: "操作",
          slotName: "operation",
          width: "120"
        }
      ],
      formConfig: [
        {
          label: "类别名称",
          prop: "alarmTypeName",
          type: "input"
        }
      ],
      rules: {
        alarmTypeName: [
          { required: true, message: "请输入告警类别名称", trigger: "blur" }
        ],
        describe: [
          { required: true, message: "请输入告警类别描述", trigger: "blur" }
        ],
        nowdataType: [
          { required: true, validator: validatePass, trigger: "change" }
        ]
      },
      // 当前数据类型选择的index
      nowdataType: [],
      // 数据类型列表
      dataTypeList: [],
      // 展示的数据类型列表
      showdatatypeList: [],
      // 搜索内容
      searchlist: {
        alarmTypeName: ""
      },
      // 选中的数据项数组 alarmTypeId组成 (此数组最多为一个)
      selectIdList: [],
      dialogTitle: "",
      dialogFormVisible: false,
      formData: {
        alarmTypeName: "",
        describe: ""
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    // 获取表格数据
    this.getTableDataList();
    this.getselectlist();
  },
  mounted() {},
  methods: {
    changeTableSort(column) {
      this.sortList = column.order
        ? [
          {
            property: column.prop,
            direction: column.order == "ascending" ? "asc" : "desc"
          }
        ]
        : [];
      this.getTableDataList();
    },
    // 添加一条数据类别
    addDataType(e) {
      this.showdatatypeList = []
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        e.forEach(item => {
          this.dataTypeList.forEach(el => {
            if (el.dataTypeId === item) {
              let addData = {
                dataTypeId: el.dataTypeId,
                dataTypeName: el.dataTypeName
              };
              this.showdatatypeList.push(addData);
            }
          })
        })
      }
    },
    // 删除一条数据
    delDataType(index) {
      if (this.nowChanceStau === "add" || this.nowChanceStau === "edit") {
        this.showdatatypeList.splice(index, 1);
        this.nowdataType.splice(index, 1)
      }
    },
    // 获取下拉数据
    getselectlist() {
      // 获取所有数据类型
      nowpagereq.getalldatalist().then((res) => {
        this.dataTypeList = res.data;
      });
    },
    getTableDataList() {
      this.loading = true;
      this.showdatatypeList = [];
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || []
      };
      if (
        this.searchlist.alarmTypeName &&
        this.searchlist.alarmTypeName.length > 0
      ) {
        let searchparams = {
          alarmTypeName: this.searchlist.alarmTypeName
        };
        nowpagereq.querybycondition(searchparams).then((res) => {
          this.loading = false;
          if (res.code === 1) {
            // this.$message.success('查询成功')
          } else {
            this.$message.error("查询失败");
          }
          let data = res.data;
          // 赋值总条数
          this.totalSize = data.length;
          // 赋值数组
          this.tableData = data;
          this.addblankmet();
          this.resetActionBar();
        });
      } else {
        nowpagereq.getlist(params).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.$message.error("查询失败");
          }
          let data = res.data;
          // 赋值总条数
          this.totalSize = data.totalElements;
          // 赋值数组
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        });
      }
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 添加
    add() {
      this.addActive = false;
      this.openDialog("add");
      this.formData = {};
    },
    // 取消
    cancel() {
      this.addActive = true;
      this.closeDialog();
      this.formData = {};
    },
    handleEdit(row) {
      this.nowdataType = []
      // console.log(this.dataTypeList, "whw");
      console.log(row);
      if (row.alarmTypeId) {
        this.formData = { ...row };
        row.alarmTypeDataTypeMapperList.forEach((el) => {
          this.nowdataType.push(el.dataTypeId)
        });
        this.showdatatypeList = row.alarmTypeDataTypeMapperList;
        this.openDialog("edit");
      }
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      let notvalue = true;
      this.selectIdList = list.map((item) => {
        if (item.alarmTypeId) {
          return item.alarmTypeId;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.selectIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      nowpagereq.dellist(this.selectIdList).then((res) => {
        if (res.code === 1) {
          this.$message.success("删除成功");
          this.getTableDataList();
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    handleDelete(data) {
      // nowpagereq.del(data).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success("删除成功");
      //     this.getTableDataList();
      //   } else {
      //     this.$message.error("删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          nowpagereq.del(data).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            // 编辑接口
            let addparams = {
              ...this.formData
            };
            addparams['alarmTypeDataTypeMapperList'] = []
            this.nowdataType.forEach(el => {
              this.dataTypeList.forEach(item => {
                if (item.dataTypeId === el) {
                  let obj = {
                    dataTypeId: item.dataTypeId,
                    dataTypeName: item.dataTypeName
                  }
                  addparams['alarmTypeDataTypeMapperList'].push(obj)
                }
              })
            })
            nowpagereq.editlist(addparams).then((res) => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.getTableDataList();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            let addparams = {
              ...this.formData
            };
            addparams['alarmTypeDataTypeMapperList'] = []
            this.nowdataType.forEach(el => {
              this.dataTypeList.forEach(item => {
                if (item.dataTypeId === el) {
                  let obj = {
                    dataTypeId: item.dataTypeId,
                    dataTypeName: item.dataTypeName
                  }
                  addparams['alarmTypeDataTypeMapperList'].push(obj)
                }
              })
            })
            // console.log(addparams); return
            nowpagereq.addlist(addparams).then((res) => {
              if (res.code === 1) {
                this.$message.success("新增成功！");
                this.closeDialog();
                this.getTableDataList();
              } else {
                this.$message.error("新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.nowdataType = [];
      this.showdatatypeList = []
      this.$nextTick(() => {
        this.$refs.formData.resetFields();
      });
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    }
  }
};
</script>

<style scoped lang="scss">
.contact-view {
  width: 100%;
  // border: #6ecae3 1px solid;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .contact-view-but {
    background-color: #409eff;
    border: 1px solid #409eff;
    color: #fff;
    width: 200px;
    height: 36px;
    line-height: 36px;
    font-size: 18px;
    margin: 5px;
    text-align: center;
    .el-icon-close {
      height: 36px;
      line-height: 36px;
      float: right;
      padding-right: 6px;
    }
  }
}
</style>
